<template>
  <div class="ai-chat-panel">
    <!-- Header -->
    <div class="chat-header">
      <div class="header-title">
        <el-icon><Cpu /></el-icon>
        <span>智能助手 (DeepSeek)</span>
      </div>
      <div class="header-actions">
        <el-button link @click="showConfig = true">
            <el-icon><Setting /></el-icon>
        </el-button>
        <el-button link @click="clearChat">
            <el-icon><Delete /></el-icon>
        </el-button>
        <el-button link @click="$emit('close')">
            <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- Message List -->
    <div class="message-list" ref="msgListRef">
      <div v-if="messages.length === 0" class="empty-state">
        <el-icon :size="40" color="#dcdfe6"><ChatDotRound /></el-icon>
        <p>有什么可以帮您？试试问我：</p>
        <div class="suggestions">
            <el-tag @click="sendSuggestion('帮我分析这个嫌疑人的资金链')">资金链分析</el-tag>
            <el-tag @click="sendSuggestion('如何排查洗钱行为？')">洗钱排查</el-tag>
            <el-tag @click="sendSuggestion('总结一下当前的案件线索')">线索总结</el-tag>
        </div>
      </div>

      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        class="message-item"
        :class="msg.role"
      >
        <div class="avatar">
            <el-icon v-if="msg.role === 'user'"><User /></el-icon>
            <el-icon v-else><Cpu /></el-icon>
        </div>
        <div class="content">
            <div class="markdown-body" v-html="renderMarkdown(msg.content)"></div>
            <div v-if="msg.loading" class="typing-indicator">
                <span>.</span><span>.</span><span>.</span>
            </div>
        </div>
      </div>
    </div>

    <!-- Input Area -->
    <div class="input-area">
      <el-input
        v-model="inputContent"
        type="textarea"
        :rows="3"
        placeholder="输入您的问题 (Ctrl+Enter 发送)..."
        @keydown.ctrl.enter="sendMessage"
      />
      <div class="input-actions">
        <!-- <el-switch v-model="useContext" active-text="关联当前数据" /> -->
        <el-button type="primary" size="small" :loading="sending" @click="sendMessage">发送</el-button>
      </div>
    </div>

    <!-- Config Dialog -->
    <el-dialog v-model="showConfig" title="AI 设置" width="400px" append-to-body>
        <el-form label-width="100px">
            <el-form-item label="服务商">
                <el-radio-group v-model="config.provider">
                    <el-radio label="deepseek">DeepSeek (官方)</el-radio>
                    <el-radio label="custom">自定义 (Local/Ollama)</el-radio>
                </el-radio-group>
            </el-form-item>

            <template v-if="config.provider === 'deepseek'">
                <el-form-item label="API Key">
                    <el-input v-model="config.apiKey" type="password" show-password placeholder="sk-..." />
                </el-form-item>
            </template>

            <template v-else>
                <el-form-item label="Base URL">
                    <el-input v-model="config.baseUrl" placeholder="http://localhost:11434/v1" />
                </el-form-item>
                <el-form-item label="Model Name">
                    <el-input v-model="config.model" placeholder="deepseek-r1:7b" />
                </el-form-item>
                <el-form-item label="API Key">
                    <el-input v-model="config.apiKey" placeholder="可选" />
                </el-form-item>
            </template>

            <el-form-item label="温度">
                <el-slider v-model="config.temperature" :min="0" :max="1" :step="0.1" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="showConfig = false">取消</el-button>
            <el-button type="primary" @click="saveConfig">保存</el-button>
        </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { Cpu, User, Setting, Close, Delete, ChatDotRound } from '@element-plus/icons-vue'
// import { marked } from 'marked' 
import { ElMessage, ElSlider } from 'element-plus'

const messages = ref([])
const inputContent = ref('')
const sending = ref(false)
const msgListRef = ref(null)
const showConfig = ref(false)

const config = ref({
    provider: 'deepseek', // virtual field
    baseUrl: 'https://api.deepseek.com/v1',
    apiKey: '',
    model: 'deepseek-chat',
    temperature: 0.7
})

// Markdown Renderer (Simple fallback if marked not installed, but usually should install it)
// For now, let's assume we might need to basic format
const renderMarkdown = (text) => {
    if (!text) return ''
    // Basic formatting for line breaks and code
    let html = text
        .replace(/\n/g, '<br>')
        .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    return html
}

onMounted(async () => {
    // Load config
    try {
        const saved = await window.electronAPI.ai.getConfig()
        if (saved.baseUrl) config.value.baseUrl = saved.baseUrl
        if (saved.apiKey) config.value.apiKey = saved.apiKey
        if (saved.model) config.value.model = saved.model
        if (saved.temperature) config.value.temperature = saved.temperature
        
        // Infer provider for UI
        if (config.value.baseUrl.includes('deepseek')) {
            config.value.provider = 'deepseek'
        } else {
            config.value.provider = 'custom'
        }
    } catch (e) {
        console.error('Failed to load config', e)
    }
})

watch(() => config.value.provider, (val) => {
    if (val === 'deepseek') {
        config.value.baseUrl = 'https://api.deepseek.com' // deepseek official
        config.value.model = 'deepseek-chat'
    } else {
        if (config.value.baseUrl.includes('deepseek')) {
            config.value.baseUrl = 'http://localhost:11434/v1' // ollama default
            config.value.model = 'deepseek-r1:7b'
        }
    }
})

const scrollToBottom = () => {
    nextTick(() => {
        if (msgListRef.value) {
            msgListRef.value.scrollTop = msgListRef.value.scrollHeight
        }
    })
}

const sendSuggestion = (text) => {
    inputContent.value = text
    sendMessage()
}

const sendMessage = async () => {
    if (!inputContent.value.trim() || sending.value) return
    
    const userMsg = inputContent.value.trim()
    messages.value.push({ role: 'user', content: userMsg })
    inputContent.value = ''
    sending.value = true
    scrollToBottom()

    // Prepare history
    const history = messages.value.map(m => ({
        role: m.role,
        content: m.content
    })).slice(-10) // Keep context reasonable

    // Add placeholder for AI
    const aiMsgIndex = messages.value.push({ role: 'assistant', content: '', loading: true }) - 1
    
    let currentContent = ''

    const cleanup = window.electronAPI.ai.chat(
        history,
        (token) => {
           currentContent += token
           messages.value[aiMsgIndex].content = currentContent
           scrollToBottom()
        },
        () => {
           messages.value[aiMsgIndex].loading = false
           sending.value = false
        },
        (err) => {
            messages.value[aiMsgIndex].content += `\n[Error: ${err}]`
            messages.value[aiMsgIndex].loading = false
            sending.value = false
        }
    )
}

const saveConfig = async () => {
    try {
        await window.electronAPI.ai.saveConfig({
            baseUrl: config.value.baseUrl,
            apiKey: config.value.apiKey,
            model: config.value.model,
            temperature: config.value.temperature
        })
        showConfig.value = false
        ElMessage.success('配置已保存')
    } catch (e) {
        ElMessage.error('保存失败: ' + e.message)
    }
}

const clearChat = () => {
    messages.value = []
}
</script>

<style scoped>
.ai-chat-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-left: 1px solid #dcdfe6;
}

.chat-header {
  height: 50px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  background: #f5f7fa;
}

.header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #303133;
}

.message-list {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #909399;
}

.suggestions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: center;
    margin-top: 15px;
}

.suggestions .el-tag {
    cursor: pointer;
}

.message-item {
    display: flex;
    gap: 12px;
}

.message-item.user {
    flex-direction: row-reverse;
}

.avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f0f2f5;
    flex-shrink: 0;
}

.message-item.user .avatar {
    background: #409eff;
    color: white;
}

.content {
    background: #f4f4f5;
    padding: 10px 15px;
    border-radius: 8px;
    max-width: 80%;
    font-size: 14px;
    line-height: 1.6;
}

.message-item.user .content {
    background: #ecf5ff;
    color: #303133;
}

.input-area {
    padding: 15px;
    border-top: 1px solid #ebeef5;
}

.input-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
}
</style>
